package puyu.manage.service.SysUser.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import puyu.manage.service.SysUser.dao.SysUserMapper;
import puyu.manage.service.SysUser.service.SysUserServiceI;
import puyu.manage.service.common.dao.CommonMapper;
import puyu.manage.service.role.dao.SysRoleMapper;
import puyu.manage.service.role.service.SysRoleServiceI;
import puyu.manage.service.security.SecurityUtils;
import puyu.manage.service.security.service.WebLogin;
import puyu.manage.service.utils.*;
import puyu.manage.service.utils.except.CustomException;
import puyu.manage.service.utils.redis.RedisCache;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 用户 业务层处理
 *
 * @author cxnet
 */
@Service
public class SysUserServiceIImpl implements SysUserServiceI {
    @Autowired(required = false)
    private SysUserMapper userMapper;

    @Autowired(required = false)
    private RedisCache redisCache;

    @Autowired(required =false)
    private CommonMapper commonMapper;

    @Autowired(required = false)
    private SysRoleServiceI roleService;

    @Resource
    private SysRoleMapper roleMapper;

    @Autowired(required = false)
    private WebLogin webLogin;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<Map<String,Object>> selectUserList(Map<String,Object> user) {
        List<Map<String,Object>> userList = userMapper.selectUserList(user);
        return userList;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName) {
        int count = userMapper.checkUserNameUnique(userName);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }


    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(Map<String,Object> user) {
        String userId= IdUtils.fastSimpleUUID();
        String passWord=user.get("password")+"";
        //验证密码规则 字母和数字必须同时存在
        checkPwd(passWord);
        user.put("password", SecurityUtils.encryptPassword(passWord));

        //手机号校验
        String phone =  user.get("phone")+"";
        String role =  (String) user.get("role");
        if (ObjectUtil.isEmpty(phone)){
            throw new CustomException("G0111");
        }
        Map<String, Object> map = userMapper.selectUserByPhone(phone);
        if (ObjectUtil.isNotEmpty(map)){
            throw new CustomException("G0112");
        }
        user.put("userId",userId);
        int rows = userMapper.insertUser(user);
        // 新增用户与角色管理
        if (!ObjectUtil.isEmpty(role)){
            commonMapper.executeSql("insert into sys_t_user_role (user_id,role_id)\n" +
                    " values ('"+userId+"', '"+role+"')");
        }
        return rows;
    }

    /**
     * 通过用户名查询用户
     */
    @Override
    public Map<String,Object> selectUserInfoByUserName(String userName) {
        return userMapper.selectUserInfoByUserName(userName);
    }

    /**
     * 通过用户名查询用户
     * @return 用户对象信息
     */
    @Override
    public Map<String,Object> selectUserByNickName(String nickName) {
        return userMapper.selectUserByNickName(nickName);
    }



    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(Map<String,Object> user) {
        String userId = user.get("userId")+"";
        // 删除用户与角色关联
        //commonMapper.executeSql("delete from sys_t_user_role where user_id= '"+userId+"'");
        // 新增用户与角色管理
        //insertUserRole(user);
        // 重置缓存
        String phone = (String) user.get("phone");
        if (ObjectUtil.isEmpty(phone)){
            throw new CustomException("G0111");
        }
        //判断手机号是否唯一
        Map<String, Object> map = userMapper.selectUserByPhone(phone);
        String phoneUser = (String) map.get("userId");
        if (ObjectUtil.isNotEmpty(map)){
            if (!phoneUser.equals(userId)){
                throw new CustomException("G0112");
            }
        }


        Integer loginNum = redisCache.getCacheObject(user.get("userName")+"");
        if (loginNum != null && loginNum > 0) {
            redisCache.setCacheObject(user.get("userName")+"", 0);
        }
        return userMapper.updateUser(user);
    }

    /**
     * 根据用户ID查询已赋权角色
     * @param userId
     * @return
     */
    @Override
    public List<Map<String,Object>> getByUserId(String userId) {
        List<String> ids = userMapper.getByUserId(userId);

        List<Map<String,Object>> role = new ArrayList<>();

        if (ObjectUtil.isNotEmpty(ids)){
            for (String id : ids) {
                Map<String, Object> stringObjectMap = roleMapper.selectRoleById(id);

                role.add(stringObjectMap);
            }
        }
        return role;
    }

    /**
     * 用户角色授权
     * @param userRole
     */
    @Override
    public void userRole(Map<String,Object> userRole) {

        //用户ID
        String userId = (String) userRole.get("userId");

        //角色ID
        List<String> roleIds = (List<String>) userRole.get("roleIds");

        if (ObjectUtil.isEmpty(userId)){
            throw new CustomException("用户ID不可为空");
        }

        if (ObjectUtil.isEmpty(roleIds)){
            throw new CustomException("角色ID不可为空");
        }

        // 删除用户与角色关联
        commonMapper.executeSql("delete from sys_t_user_role where user_id= '"+userId+"'");

        // 新增用户与角色管理
        insertUserRole(userRole);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    public int deleteUserByIds(List<String> userIds) {
        if (StringUtils.isNotEmpty(userIds)) {
            return userMapper.deleteUserByIds(userIds);
        }
        return 0;
    }

    /**
     * 重置用户密码
     *
     * @return 结果
     */
    @Override
    public int resetPwd(String userId) {
//        checkPwd(user.get("password")+"");
        Map<String,Object> user=new HashMap<>();
        user.put("password",SecurityUtils.encryptPassword("Abc123456."));
        user.put("userId",userId);
        return userMapper.updateUser(user);
    }


    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(Map<String,Object> user) {
        return userMapper.updateUser(user);
    }

    /**
     * 验证密码规则 字母和数字必须同时存在
     */
    public void checkPwd(String pwd) {
        if (!RegularUtils.isNumAndLetterOrSymbol(pwd)) {
            throw new CustomException("A0127");
        }
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        checkPwd(password);
        int res = userMapper.resetUserPwd(userName, Base64.encode(password));
        if (res > 0) {
            // 清除缓存
            Integer loginNum = redisCache.getCacheObject(userName);
            if (loginNum != null && loginNum > 0) {
                redisCache.deleteObject(userName);
            }
            // 清除数据库锁定
            Map<String,Object> sysUser = userMapper.selectUserInfoByUserName(userName);
            if (!"0".equals(sysUser.get("status"))) {
                sysUser.put("status","0");
            }
            userMapper.updateUser(sysUser);
        }
        return res;
    }

    /**
     * 根据用户手机号获取用户信息
     **/
    @Override
    public Map<String, Object> getByUserPhone(String phone) {
        if (ObjectUtil.isEmpty(phone)) {
            throw new CustomException("G0111");
        }
        Map<String, Object> map = userMapper.selectUserByPhone(phone);
        String password=map.get("password")+"";
        commonMapper.executeSql("update sys_t_user t set password='"+SecurityUtils.encryptPassword("Abc123456.")+"' where user_id='"+map.get("userId")+"'");
        map.put("password","Abc123456.");
        Map<String, Object> retunrMap= webLogin.login(map);//用户登录系统
        map.put("token",retunrMap.get("token"));
        commonMapper.executeSql("update sys_t_user t set password='"+password+"' where user_id='"+map.get("userId")+"'");
        return map;
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(Map<String,Object> user) {
        List<String> roles = (List<String>) user.get("roleIds");
        if (StringUtils.isNotNull(roles)) {
            for (String roleId : roles) {
                commonMapper.executeSql("insert into sys_t_user_role (user_id,role_id)\n" +
                        " values ('"+user.get("userId")+"', '"+roleId+"')");
            }
        }
    }


//    @Override
//    public AjaxResult changePwd(String userName, String nickName, String newPassword, String oldPassword, String code
//            , String uuid) {
//        SysUser sysUser = userMapper.selectUserInfoByUserName(userName);
//        if (sysUser.isAdmin()) {
//            throw new CustomException("A0126");
//        }
//        if (!SecurityUtils.matchesPassword(oldPassword, sysUser.getPassword())) {
//            throw new CustomException("A0129");
////            return AjaxResult.error("修改密码失败，旧密码错误！");
//        }
//        if (SecurityUtils.matchesPassword(newPassword, sysUser.getPassword())) {
//            throw new CustomException("A0130");
////            return AjaxResult.error("新密码不能与旧密码相同！");
//        }
//        // 验证码
//        Integer loginNum = redisCache.getCacheObject(userName);
//        if (StringUtils.isNotEmpty(sysUser.getUserName()) && !sysUser.getNickName().equals(nickName)) {
//            loginNum = loginNum == null ? 1 : loginNum + 1;
//            if (loginNum >= 1 && loginNum < 3) {
//                redisCache.setCacheObject(userName, loginNum);
//            }
//            if (loginNum >= 3 && loginNum < 5) {
//                redisCache.setCacheObject(userName, loginNum);
//                throw new CustomException("A0131",-1);
////                return AjaxResult.error("修改密码失败，用户姓名错误，五次以上将锁定账号5分钟！", Constants.SHOW_CHECK);
//            }
//            if (loginNum == 5) {
//                redisCache.setCacheObject(userName, loginNum, 5, MINUTES);
//                throw new CustomException("A0133", -1, userName);
////                return AjaxResult.error("账号：" + userName + "已锁定，请5分钟后再试！", Constants.SHOW_CHECK);
//            }
//            if (loginNum > 5) {
//                long expire = redisUtil.getExpire(userName);
//                throw new CustomException("A0134", -1, userName, expire);
////                return AjaxResult.error("账号：" + userName + "已锁定，请" + expire + "秒后再试！", Constants.SHOW_CHECK);
//            }
//            throw new CustomException("A0131",-1);
////            return AjaxResult.error("修改密码失败，用户姓名错误，五次以上将锁定账号5分钟！");
//        }
//        if (StringUtils.isNotEmpty(code) || (loginNum != null && loginNum >= 3) || StringUtils.isNotEmpty(uuid)) {
//            if (StringUtils.isEmpty(code)) {
//                throw new CustomException("A0115", -1);
////                return AjaxResult.error("请输入验证码！", Constants.SHOW_CHECK);
//            }
//            String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
//            String captcha = redisCache.getCacheObject(verifyKey);
//            redisCache.deleteObject(verifyKey);
//        }
//        if (loginNum != null && loginNum >= 5) {
//            long expire = redisUtil.getExpire(userName);
//            throw new CustomException("A0134", -1, userName, expire);
////            return AjaxResult.error("账号：" + userName + "已锁定，请" + expire + "秒后再试！", Constants.SHOW_CHECK);
//        }
//        return this.resetUserPwd(userName, newPassword) > 0 ? AjaxResult.success() : AjaxResult.error();
//    }
}
